package com.ricky.websocket;

import com.ricky.mapper.HotelServiceMsgMapper;
import com.ricky.model.HotelServiceMsg;
import com.ricky.model.example.HotelServiceMsgExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * 聊天控制器
 */
@Controller
public class GreetingController {
    /**session操作类*/
    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;
    /**消息发送工具*/
    @Autowired
    private SimpMessagingTemplate template;

    @Autowired
    private HotelServiceMsgMapper hotelServiceMsgMapper;

    @RequestMapping(value = "/index")
    public  String index(){
        return "/index";
    }
    @RequestMapping(value = "/msg/message")
    public  String ToMessage(){
        return "/message";
    }
    @RequestMapping(value = "/msg/messaget2")
    public  String ToMessaget2(){
        return "/messaget2";
    }
    @RequestMapping(value = "/msg/hotel1")
    public  String ToHotelNo2(){
        return "/hotelNo1";
    }
    @RequestMapping(value = "/msg/hotel2")
    public  String ToHotelNo1(){
        return "/hotelNo2";
    }
    @RequestMapping(value = "/msg/guest1")
    public  String ToGuest1(){
        return "/guestNo1";
    }
    @RequestMapping(value = "/msg/guest2")
    public  String ToGuest2(){
        return "/guestNo2";
    }



    /**
     * 用户广播
     * 发送消息广播  用于内部发送使用
     * @param request
     * @return

    @GetMapping(value = "/msg/sendcommuser")
    public  @ResponseBody
    OutMessage SendToCommUserMessage(HttpServletRequest request){
        List<String> keys=webAgentSessionRegistry.getAllSessionIds().entrySet()
                .stream().map(Map.Entry::getKey)
                .collect(Collectors.toList());
        Date date=new Date();
        keys.forEach(x->{
            String sessionId=webAgentSessionRegistry.getSessionIds(x).stream().findFirst().get().toString();
            template.convertAndSendToUser(sessionId,"/topic/greetings",new OutMessage("commmsg：allsend, " + "send  comm" +date.getTime()+ "!"),createHeaders(sessionId));

        });
         return new OutMessage("sendcommuser, " + new Date() + "!");
    }*/




    /**
     * 同样的发送消息   只不过是ws版本  http请求不能访问
     * 根据用户key发送消息
     * @param message
     * @return
     * @throws Exception
     */
    @MessageMapping("/msg/hellosingle")
    public void greeting2(InMessage message) throws Exception {
        if(!message.getConnect()){
            HotelServiceMsgExample example = new HotelServiceMsgExample();
            HotelServiceMsgExample.Criteria criteria = example.createCriteria();
            criteria.andHotelCodeEqualTo(message.getFromUsername()).andUserNameEqualTo(message.getToUser());
            example.or().andHotelCodeEqualTo(message.getToUser()).andUserNameEqualTo(message.getFromUsername());
            String login = message.getFromUsername();
            example.setOrderByClause("create_time asc");
            List<HotelServiceMsg> list = hotelServiceMsgMapper.selectByExample(example);
            Set<String> set = webAgentSessionRegistry.getSessionIds(message.getFromUsername());
            for(HotelServiceMsg vo:list){
                message = new InMessage();
                message.setFromUsername(vo.getUserName());
                message.setConnect(false);
                message.setToUser(login);
                message.setMsg(vo.getMsg());
                //这里没做校验

                for (String sessionId:set){
                    template.convertAndSendToUser(sessionId,"/topic/greetings",new OutMessage(message.getFromUsername()+":<br/>"+message.getMsg(),message.getFromUsername()),createHeaders(sessionId));
                }

            }
            return;
        }

        //这里没做校验
        Set<String> set = webAgentSessionRegistry.getSessionIds(message.getToUser());
        Boolean flag = false;
        for (String sessionId:set){
            template.convertAndSendToUser(sessionId,"/topic/greetings",new OutMessage(message.getFromUsername()+":<br/>"+message.getMsg(),message.getFromUsername()),createHeaders(sessionId));
            flag = true;
        }
        HotelServiceMsg hotelServiceMsg = new HotelServiceMsg();
        hotelServiceMsg.setMsg(message.getMsg());
        hotelServiceMsg.setUserName(message.getFromUsername());
        hotelServiceMsg.setHotelCode(message.getToUser());
        hotelServiceMsg.setUserId(1);
        hotelServiceMsg.setStatus(1);
        if(flag){
            hotelServiceMsg.setStatus(0);
            hotelServiceMsg.setUpdateTime(new Date());
        }
        hotelServiceMsg.setCreateTime(new Date());
        hotelServiceMsgMapper.insertSelective(hotelServiceMsg);


    }
    private MessageHeaders createHeaders(String sessionId) {
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        return headerAccessor.getMessageHeaders();
    }

}
